<template>
  <div v-loading="loading" class="w-full">
    <h3 style="display: inline-block">{{ container.name }}</h3>
    <el-form>
      <el-row :gutter="20" style="margin-top: 20px" class="row-box">
        <el-col :span="container.volumeMounts ? 8 : 24">
          <el-card class="el-card" :header="$t('business.pod.image')">
            <el-form-item
              v-if="containerStatusStates[container.name] != ''"
              label="State"
            >
              <span>
                <pre>{{ containerStatusStates[container.name] }}</pre>
              </span>
            </el-form-item>
            <el-form-item
              v-if="containerStatusLastStates[container.name] != ''"
              label="LastState"
            >
              <span>
                <pre>{{ containerStatusLastStates[container.name] }}</pre>
              </span>
            </el-form-item>
            <el-form-item :label="$t('business.workload.pull_policy')">
              <span>{{ container.imagePullPolicy }}</span>
            </el-form-item>
            <el-form-item :label="$t('business.workload.container_image')">
              <span>{{ container.image }}</span>
            </el-form-item>

            <div
              v-if="container.workingDir || container.command || container.args"
            >
              <h4 style="display: inline-block">
                {{ $t("business.workload.command") }}
              </h4>
              <el-form-item
                v-if="container.workingDir"
                :label="$t('business.workload.working_dir')"
              >
                <span>{{ container.workingDir }}</span>
              </el-form-item>
              <el-form-item
                v-if="container.command"
                :label="$t('business.workload.commands')"
              >
                <el-tag
                  v-for="(item, index) in container.command"
                  :key="index"
                  type="success"
                  >{{ item }}</el-tag
                >
              </el-form-item>
              <el-form-item
                v-if="container.args"
                :label="$t('business.workload.arguments')"
              >
                <el-tag
                  v-for="(item, index) in container.args"
                  :key="index"
                  type="success"
                  >{{ item }}</el-tag
                >
              </el-form-item>
            </div>

            <div v-if="container.ports">
              <h4 style="display: inline-block">
                {{ $t("business.workload.port") }}
              </h4>
              <complex-table
                :header-cell-style="{ background: '#19191c' }"
                :data="container.ports"
              >
                <el-table-column
                  :label="$t('commons.table.name')"
                  prop="name"
                  show-overflow-tooltip
                  fix
                />
                <el-table-column
                  :label="$t('business.workload.container_port')"
                  prop="containerPort"
                  show-overflow-tooltip
                  fix
                />
                <el-table-column
                  :label="$t('business.workload.protocol')"
                  prop="protocol"
                  show-overflow-tooltip
                  fix
                />
                <el-table-column
                  :label="$t('business.workload.host_port')"
                  prop="hostPort"
                  show-overflow-tooltip
                  fix
                />
              </complex-table>
            </div>
          </el-card>
        </el-col>

        <el-col v-if="container.volumeMounts" :span="16">
          <el-card class="el-card" :title="$t('business.network.port')">
            <div v-if="container.env">
              <h4 style="display: inline-block">
                {{ $t("business.workload.variable") }}
              </h4>
              <el-form-item :label="$t('business.workload.variable')">
                <el-tag
                  v-for="(item, index) in container.env"
                  :key="index"
                  type="success"
                  style="margin-right: 10px"
                  >{{ item.name + " = " + item.value }}</el-tag
                >
              </el-form-item>
            </div>

            <div v-if="container.volumeMounts">
              <h4 style="display: inline-block">
                {{ $t("business.workload.mount") }}
              </h4>
              <complex-table
                :header-cell-style="{ background: '#19191c' }"
                :data="container.volumeMounts"
              >
                <el-table-column
                  :label="$t('commons.table.name')"
                  prop="name"
                  show-overflow-tooltip
                  fix
                />
                <el-table-column
                  :label="$t('business.workload.path')"
                  prop="mountPath"
                  show-overflow-tooltip
                  fix
                />
                <el-table-column
                  :label="$t('business.workload.read_only')"
                  prop="readOnly"
                  show-overflow-tooltip
                  fix
                />
                <el-table-column
                  :label="$t('business.workload.sub_path_in_volume')"
                  prop="subPath"
                  show-overflow-tooltip
                  fix
                />
              </complex-table>
            </div>

            <div
              v-if="
                container.resources &&
                (container.resources.limits || container.resources.requests)
              "
            >
              <h4 style="display: inline-block">
                {{ $t("business.workload.resource") }}
              </h4>
              <el-row :gutter="20">
                <div v-if="container.resources && container.resources.requests">
                  <el-col v-if="container.resources.requests.cpu" :span="12">
                    <el-form-item
                      :label="
                        'CPU ' +
                        $t('business.workload.reservation') +
                        ' (mCPUs)'
                      "
                    >
                      <span>{{ container.resources.requests.cpu }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col v-if="container.resources.requests.cpu" :span="12">
                    <el-form-item
                      :label="
                        $t('business.workload.memory') +
                        $t('business.workload.reservation') +
                        ' (Mi)'
                      "
                    >
                      <span>{{ container.resources.requests.memory }}</span>
                    </el-form-item>
                  </el-col>
                </div>
                <div v-if="container.resources && container.resources.limits">
                  <el-col v-if="container.resources.limits.cpu" :span="12">
                    <el-form-item
                      :label="
                        'CPU ' + $t('business.workload.limit') + ' (mCPUs)'
                      "
                    >
                      <span>{{ container.resources.limits.cpu }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col v-if="container.resources.limits.memory" :span="12">
                    <el-form-item
                      :label="
                        $t('business.workload.memory') +
                        $t('business.workload.limit') +
                        ' (Mi)'
                      "
                    >
                      <span>{{ container.resources.limits.memory }}</span>
                    </el-form-item>
                  </el-col>
                </div>
              </el-row>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <div
        v-if="
          container.livenessProbe ||
          container.readinessProbe ||
          container.startupProbe
        "
      >
        <h4>{{ $t("business.workload.health_check") }}</h4>
        <el-row :gutter="20" class="row-box">
          <el-col
            v-for="(item, index) in container.healthCheck"
            :key="index"
            :span="6"
          >
            <el-card class="el-card">
              <h4>{{ item._type }}</h4>
              <div v-if="item._model.exec">
                <el-form-item :label="$t('business.workload.type')">
                  <span>exec</span>
                </el-form-item>
                <el-form-item
                  v-if="item._model.exec && item._model.exec.command"
                  :label="$t('business.workload.command')"
                >
                  <div
                    v-for="(row, index) in item._model.exec.command"
                    :key="index"
                  >
                    <el-tag v-if="row.length < 200" type="success">{{
                      row
                    }}</el-tag>
                    <div
                      v-else
                      style="background-color: #1f261e; line-height: 20px"
                    >
                      <span class="spanStyle">{{ row }}</span>
                    </div>
                  </div>
                </el-form-item>
              </div>
              <div v-if="item._model.tcpSocket">
                <el-form-item :label="$t('business.workload.type')">
                  <span>tcpSocket</span>
                </el-form-item>
                <el-form-item
                  v-if="item._model.exec && item._model.exec.port"
                  :label="$t('business.network.port')"
                >
                  <span>{{ item._model.exec.port }}</span>
                </el-form-item>
              </div>
              <div v-if="item._model.httpGet">
                <el-form-item :label="$t('business.workload.type')">
                  <span>httpGet</span>
                </el-form-item>
                <el-form-item
                  v-if="item._model.httpGet && item._model.httpGet.path"
                  :label="$t('business.workload.check_path')"
                >
                  <span>{{ item._model.httpGet.path }}</span>
                </el-form-item>
                <el-form-item
                  v-if="item._model.httpGet && item._model.httpGet.port"
                  :label="$t('business.workload.check_port')"
                >
                  <span>{{ item._model.httpGet.port }}</span>
                </el-form-item>
              </div>
              <div v-if="item._model.httpsGet">
                <el-form-item :label="$t('business.workload.type')">
                  <span>httpsGet</span>
                </el-form-item>
                <el-form-item
                  v-if="item._model.httpGet && item._model.httpsGet.path"
                  :label="$t('business.workload.check_path')"
                >
                  <span>{{ item._model.httpsGet.path }}</span>
                </el-form-item>
                <el-form-item
                  v-if="item._model.httpsGet && item._model.httpsGet.port"
                  :label="$t('business.workload.check_port')"
                >
                  <span>{{ item._model.httpsGet.port }}</span>
                </el-form-item>
              </div>
              <el-form-item
                v-if="item._model.failureThreshold"
                :label="$t('business.workload.failure_threshold')"
              >
                <span>{{ item._model.failureThreshold }}</span>
              </el-form-item>
              <el-form-item
                v-if="item._model.initialDelaySeconds"
                :label="$t('business.workload.initial_delay')"
              >
                <span>{{ item._model.initialDelaySeconds }}</span>
              </el-form-item>
              <el-form-item
                v-if="item._model.periodSeconds"
                :label="$t('business.workload.check_interval')"
              >
                <span>{{ item._model.periodSeconds }}</span>
              </el-form-item>
              <el-form-item
                v-if="item._model.successThreshold"
                :label="$t('business.workload.seccess_threshold')"
              >
                <span>{{ item._model.successThreshold }}</span>
              </el-form-item>
              <el-form-item
                v-if="item._model.timeoutSeconds"
                :label="$t('business.workload.timeout')"
              >
                <span>{{ item._model.timeoutSeconds }}</span>
              </el-form-item>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <br />
    <el-row style="margin-top: 20px">
      <KoDetailContainersMetrics
        :containerInfo="containerInfo"
        :cluster="cluster"
        :podInfo="podInfo"
      />
    </el-row>
  </div>
</template>

<script setup lang="ts">
import ComplexTable from "@/views/domain/kubeHud/views/components/complex-table/index.vue";
import KoDetailContainersMetrics from "@/views/domain/kubeHud/views/components/detail/detail-containers-metrics.vue";
import { ref, watch } from "vue";
import { Container } from "../../../api/k8s";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

type Prop = {
  cluster: string;
  // podInfo: any;
  containerInfo: any;
};
const props = defineProps<Prop>();
const podInfo = defineModel<any>("podInfo");

const loading = ref(true);
const activeNames = ref(0);
const container = ref<Container & Record<string, any>>({
  image: "",
  resources: {},
  healthCheck: []
});
const containerStatuses = ref({});
const containerStatusStates = ref({});
const containerStatusLastStates = ref({});

const reloadYaml = (yamlData: any, updateContainer?: boolean) => {
  if (!yamlData) return;
  if (yamlData.spec?.containers) {
    if (props.containerInfo.type === "init-container") {
      for (const item of yamlData.spec.initContainers) {
        if (item.name === props.containerInfo.name) {
          container.value = item;
          break;
        }
      }
    } else {
      for (const item of yamlData.spec.containers) {
        if (item.name === props.containerInfo.name) {
          container.value = item;
        }
      }
    }

    container.value.healthCheck = [];
    if (container.value.livenessProbe) {
      container.value.healthCheck.push({
        _type: t("business.workload.liveness_check"),
        _model: container.value.livenessProbe
      });
    }
    if (container.value.readinessProbe) {
      container.value.healthCheck.push({
        _type: t("business.workload.readiness_check"),
        _model: container.value.readinessProbe
      });
    }
    if (container.value.startupProbe) {
      container.value.healthCheck.push({
        _type: t("business.workload.startup_check"),
        _model: container.value.startupProbe
      });
    }
    if (container.value.healthCheck.length === 0) {
      delete container.value.healthCheck;
    }

    loading.value = false;
  }

  if (updateContainer) {
    containerStatuses.value = {};
    yamlData.status?.containerStatuses?.forEach((item: any) => {
      containerStatuses.value[item.name] = item;
      containerStatusStates.value[item.name] = getContainerStatusKey(
        item.name,
        "state"
      );
      containerStatusLastStates.value[item.name] = getContainerStatusKey(
        item.name,
        "lastState"
      );
    });
  }
};

const getContainerStatusKey = (containerName: string, key: string) => {
  const status = containerStatuses.value[containerName];
  if (!status) return "";
  let state = "\n";
  if (status[key]) {
    for (const k of Object.keys(status[key])) {
      state += k + "\n";
      for (const sk of Object.keys(status[key][k])) {
        state += sk + ":" + status[key][k][sk] + "\n";
      }
    }
  }
  return state;
};

watch(
  () => podInfo.value,
  newpodInfo => {
    if (newpodInfo) {
      reloadYaml(newpodInfo, true);
    }
  },
  { immediate: true }
);

watch(
  () => props.containerInfo,
  newContainerInfo => {
    if (newContainerInfo) {
      reloadYaml(podInfo.value);
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.spanStyle {
  display: block;
  padding-left: 10px;
  margin-top: 5px;
  font-size: 12px;
  color: #67c23a;
  white-space: pre;
}
</style>
